import { defineStore } from 'pinia'
import { Home } from '@/api';
import { useRoute } from "vue-router";
import { ref, computed, watch } from "vue";

// 定义仓库--组合式
export let useNewMenusStore = defineStore('newMenu', () => {
    // state--菜单列表
    let menuList = ref([]);
    let route = useRoute();
    // 当前路由地址
    let curRoute = ref("");

    // action--获取菜单列表(树形结构)
    let obtain = async () => {
        let { status, msg, data } = await Home.menus();
        if (status === 200) {
            menuList.value = data.menus;
        } else {
            ElNotification.error(msg);
        }
    }

    // 当前菜单对象
    let cur_menu = computed(() => {
        let current = {};
        menuList.value.forEach((item) => {
            if (item.path == "/admin/home/") {
                current = item;
            } else {
                item.children.forEach((menu) => {
                    if (menu.path == curRoute.value) {
                        current = menu;
                    }
                });
            }
        });
        return current;
    })

    // 当前路由父级
    let cur_menu_parent = computed(() => {
        let cur_parent = {};
        menuList.value.forEach((item) => {
            if (item.id == cur_menu.value.pid) {
                cur_parent = item;
                return;
            }
        });
        return cur_parent;
    })

    // 当前二级菜单列表
    let cur_menu_2nd = computed(() => {
        return cur_menu_parent.value.children;
    })

    // 监听路由
    watch(
        () => route.path,
        (newValue) => {
            curRoute.value = newValue;
        },
        { immediate: true }
    )

    // 可以提前写好return
    return { menuList, obtain, cur_menu, cur_menu_parent, cur_menu_2nd, curRoute }
});